package com.cskaoyan.config;

import com.cskaoyan.dao.adminmanage.AdminMapper;
import com.cskaoyan.model.realm.AdminLoginAdminData;
import com.cskaoyan.model.realm.UsernamePasswordTypeToken;
import com.cskaoyan.model.wx.wxloginbean.UserInfo;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * @Author:
 * @description:
 * @keypoint:
 * @tags:
 * @related:
 */
@Component
public class AdminRealm extends AuthorizingRealm {
    //todo admin模块的

    @Autowired
    AdminMapper adminMapper;

    /**
     * 授权
     *
     * @param principalCollection
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        //首先获得当前用户信息 → doGetAuthen方法封装的第一个参数
        AdminLoginAdminData primaryPrincipal = (AdminLoginAdminData) principalCollection.getPrimaryPrincipal();
        //根据用户信息查询权限列表
        List<String> perms = primaryPrincipal.getPerms();
        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
        simpleAuthorizationInfo.addStringPermissions(perms);
        return simpleAuthorizationInfo;
    }



    /**
     * 认证
     *
     * @param authenticationToken
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        UsernamePasswordTypeToken token = (UsernamePasswordTypeToken) authenticationToken;
        String adminName = (String) token.getPrincipal();
        String host = token.getHost();

        //从数据库里面取出admin的信息
        AdminLoginAdminData admin = adminMapper.selectAdminPasswordByAdminName(adminName);
/*
        Integer[] integers = objectMapper.readValue(adminRoles, Integer[].class);
*/

        Integer[] integers = admin.getRoleIds();
        List<String> rolesName =  adminMapper.selectRolesNameByRolesId(integers);

        List<String> permsName = adminMapper.selectPermsByRolesId(integers);
        admin.setPerms(permsName);
        admin.setRoleNames(rolesName);
        String credentials = admin.getPassword();

        admin.setLast_login_ip(host);

        //第一个参数是放进subject里面的东西，
        return new SimpleAuthenticationInfo(admin, credentials, getName());

    }

}
